import java.util.*;
import java.security.interfaces.*;
import java.math.*;
import java.io.*;


//非对称加密-RSA算法2
//获取公钥私钥，并进行加密，获取密文
public class Enc_RSA {
    public static void main(String args[]) throws Exception {

        Scanner sc = new Scanner ( System.in );
        System.out.println ( "输入需要加密的文本" );
        String s = sc.nextLine ();
        // 从公钥文件Skey_RSA_pub.dat中读取公钥并强制转换为RSAPublicKey类型
        FileInputStream f = new FileInputStream ( "Skey_RSA_pub.dat" );
        ObjectInputStream b = new ObjectInputStream ( f );
        RSAPublicKey pbk = (RSAPublicKey) b.readObject ();
        // 获取公钥的参数(e, n)
        BigInteger e = pbk.getPublicExponent ();
        BigInteger n = pbk.getModulus ();
        System.out.println ( "e= " + e );
        System.out.println ( "n= " + n );
        // 明文 m
        //为了用整数表达这个字符串，使用字符串的getBytes( )方法将其转换为byte类型数组
        byte ptext[] = s.getBytes ( "utf8" );
        BigInteger m = new BigInteger ( ptext );
        // 执行计算并返回密文c,打印密文
        BigInteger c = m.modPow ( e, n );
        System.out.println ( "密文： " + c );
        // 密文以字符串形式保存在文件中
        String cs = c.toString ();
        BufferedWriter out = new BufferedWriter ( new OutputStreamWriter (new FileOutputStream ( "Enc_RSA.dat" ) ) );
        out.write ( cs, 0, cs.length () );
        out.close ();

    }
}
